import { createRouter, createWebHistory } from "vue-router";
import Layout from "@/views/layout/index.vue";
import Cart from "@/views/layout/cart.vue";
import Category from "@/views/layout/category.vue";
import Home from "@/views/layout/home.vue";
import User from "@/views/layout/user.vue";
import Login from "@/views/login/index.vue";
import MyOrder from "@/views/myorder/index.vue";
import Pay from "@/views/pay/index.vue";
import ProDetail from "@/views/prodetail/index.vue";
import Search from "@/views/search/index.vue";
import SearchList from "@/views/search/list.vue";
import { useUserStore } from "@/stores";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: Layout,
      redirect: "/home",
      children: [
        { path: "/cart", component: Cart },
        { path: "/category", component: Category },
        { path: "/home", component: Home },
        { path: "/user", component: User },
      ],
    },
    { path: "/login", component: Login },
    { path: "/myorder", component: MyOrder },
    { path: "/pay", component: Pay },
    { path: "/prodetail/:goodsId", component: ProDetail },
    { path: "/search", component: Search },
    { path: "/searchlist", component: SearchList },
  ],
});

const authUrls = ["/myorder", "/pay"];
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  if (authUrls.includes(to.path) && !userStore.token) {
    next("/login");
  } else {
    next();
  }
});

export default router;
